package com.prosay.jdbc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 
* @ClassName: Test 
* @Description: 测试模拟tomcat服务器 
* @author 猿说教育-Jame
* @date 2017年6月3日 下午8:46:53 
*
 */
public class Test {
	public static void main(String [] args){
		try {
			//在操作系统开放8080端口提供给外部访问
			ServerSocket server = new ServerSocket(8080);
			System.out.println("猿说教育tomcat服务器启动………………");
			//等待浏览器访问
			Socket socket = server.accept();
			System.out.println("浏览器请求成功！！");
			InputStream in = socket.getInputStream();
			//字节流转字符流
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String tmp = "";
			while((tmp=reader.readLine())!=null&&tmp.length()>0){
				str.append(tmp);
				str.append("\r\n");
			}
			System.out.println(str.toString());
			//d:\\web 作为系统的根目录
			String webRoot = "d:\\web";
			String[] msgs = str.toString().split(" ");
			OutputStream out  = socket.getOutputStream();
			PrintWriter writer = new PrintWriter(new OutputStreamWriter(out));
			writer.println("HTTP/1.1 200 OK");
			writer.println("Content-Type: text/html;charset=utf-8");
			writer.println();
			writer.flush();
			if(msgs.length>2){
				//OutputStream out = socket.getOutputStream();
				StringBuilder strb = new StringBuilder();
				
				//out.write("HTTP/1.1 200 OK".getBytes());
				//out.write("Content-Type: text/html;charset=utf-8".getBytes());
				//out.write("\n".getBytes());
				FileInputStream fileIn = new FileInputStream(new File(webRoot+msgs[1]));
				byte[] buf = new byte[1024];
				int length = 0;		
				while((length=fileIn.read(buf))!=-1){
					out.write(buf,0,length);
				}
				fileIn.close();
				out.close();
			}
			
			//PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
			//writer.println("HTTP/1.1 200 OK");
			//writer.println("Content-Type: text/html;charset=utf-8");
			//writer.println();
			//writer.println("欢迎使用猿说教育Web应用服务器！！！");
			//writer.flush();
			//writer.close();
			System.out.println("响应完成");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
